var timeout_json = function(data, $window) {
	if(data.returnCode == 999994) {
		var ss = 3;
		layer.msg(data.returnMessage + "！<strong class='Ajax_Out'>" + ss + "</strong> 秒后前往登录页", 50, -1);
		var picInt = setInterval(function() {
			if(ss >= 1) {
				ss = ss - 1;
				$('.Ajax_Out').text(ss);
			} else {
				clearInterval(picInt);
				try {
					$window.parent.location.href = data.returnData;
					$window.location.href = data.returnData;
				} catch(e) {
					log('timeout!')
				}
			}
		}, 1000);
		return false;
	}
}

var app = angular.module("editApp", []),
	c_id = UI.getParameterByName('id'),
	opt_type;
app.config(function($httpProvider) {
	$httpProvider.defaults.headers.put['Content-Type'] = 'application/x-www-form-urlencoded';
	$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
	$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
});

var domain_id1 = "";
app.controller('editCtrl', function($scope, $http, $window, $timeout, $location) {
	var vm = $scope.vm = {
		channel_id: null,
		channel_name: "",
		channel_url: "",
		channel_type: "",
		tagvalue_name: "",
		tagvalue_id: null,
		domainl_id: null,
		domain_name: "",
		domain_delete: null,
	};

	var key = $scope.vv = {
		c_id: c_id
	};
	//避免当快速多次点击确定按钮时，重复新增数据
	var avoidDup = true;
	$scope.domAjax = function(e) {
		if((e === "release")) {
			if(avoidDup==false){
				return false;
			}
			//获取页面上的IDS
			var $selects = $(".editExaDataBtn");
			$.each($selects, function(i, n) {
				var dd = $(n).attr("ids");
				var tag = $(n).attr("type");
				$scope.vm[eval('tag')] = dd;
			});
			domainlId = $("#domainIdSel").val();
			if(domainlId==""){
				domainlId=0;
			}
			vm.channel_type = $("#setType").val();
			//设置参数
			var params = {
				channel_id: $scope.vm.channel_id,
				channel_name: $scope.vm.channel_name,
				channel_url: $scope.vm.channel_url,
				domainl_id: domainlId,
				tagvalue_id: $scope.vm.tagvalue_id,
				channel_type: $scope.vm.channel_type,
			};
			//验证站点、频道分类
			$scope.flagChannelSelectType = false;
//			$scope.flagSiteSelectType = false;
			
			if($("#setType").val()!="" && params.channel_name!=null && params.channel_url!=null){
				var urls = ['channel/addChannel.do', 'channel/modifyChannel.do'];
//				//验证url地址
//				var strReg = "^((https|http|ftp|rtsp|mms)?://)(([a-zA-Z0-9\._-]+\.[a-zA-Z]{2,6})|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,4})*(/[a-zA-Z0-9\&%_\./-~-]*)?";
//				var re = new RegExp(strReg);
//				if(!re.test($.trim(params.channel_url))) {
//					layer.msg("请输入有效的频道网址",2,-1);
//					return false;
//				}
				avoidDup =false;
				$.ajax({
					type: "POST",
					url: basePath + urls[opt_type],
					data: params,
					error: function(request) {
						layer.msg("操作失败，请刷新重试！", 2, -1);
					},
					success: function(data) {
						var j = timeout_json(data, $window);
						if(j == false) {
							return false;
						}
						if(data.returnCode == 10000) {
							layer.msg(data.returnMessage, 1, 10);
							$timeout(function(){
								if(opt_type==1){
									try {
										window.parent.$(".dtab").find('#jsgo a.cur').trigger('click');
									} catch(e) {}
									window.parent.layer.closeAll();
								}else{
									var index = parent.layer.getFrameIndex(window.name);
									try {
										window.parent.$('#Msearch').trigger('click');
									} catch(e) {}
									parent.layer.close(index);
								}
							},1000);
						} else {
							layer.msg(data.returnMessage, 2, -1);
							avoidDup =true;
							return false;
						}
					}
				});
			}else{
				if($("#setType").val()==""){
					$scope.flagChannelSelectType = true;
				}
//				if(vm.domain_name==""){
//					$scope.flagSiteSelectType = true;
//				}
			}
		}
	};
	$scope.doCheckChange = function(e, isCheck) {
		changeCheck(e, isCheck);
	}
	//初始化数据
	$scope.initData = function(e) {
		if(vm.domain_delete == 0) {
			$("#sName").val("[已删除站点] " + vm.domain_name);
		} else {
			$("#sName").val(vm.domain_name);
		}
		$("#domainIdSel").val(vm.domainl_id),$("#setType").val(vm.channel_type);
		if(vm.channel_type=="News"){
			$("#channel_typeId").text("新闻");
		}else if(vm.channel_type=="BBS"){
			$("#channel_typeId").text("论坛");
		}
		
		//标签
//		idArr = new Array();
//		nameArr = new Array();
//		if(vm.tagvalues != undefined && vm.tagvalues.length > 0) {
//			$.each(vm.tagvalues, function(i, n) {
//				idArr.push(n.tagvalue_id);
//				nameArr.push(n.tag_value);
//			});
//			vm.tagvalue_id = idArr.join(",");
//			vm.tagvalue_name = nameArr.join(",");
//		}
	}

	//查询出数据初始化
	if(key.c_id != undefined) {
		opt_type = 1;
		$http.get(basePath + 'channel/queryById.do?channel_id=' + key.c_id).success(function(data) {
			vm = $scope.vm = data.returnData;
			//需求变化致以下被注释
//			if(content.list != null && content.list != undefined) {
//				var list = content.list;
//				var arr1 = new Array();
//				var arr2 = new Array();
//				var arr3 = new Array();
//				$scope.content.tag_value = "";
//				$scope.content.tag_type = "";
//				$scope.content.tagvalue_id = "";
//				$.each(list, function(i, n) {
//					arr1.push(n.tag_value);
//					arr2.push(n.tag_type);
//					arr3.push(n.tagvalue_id);
//				});
//				if(arr1.length > 0) {
//					$scope.content.tag_value = arr1.join(",");
//					$scope.content.tag_type = arr2.join(",");
//					$scope.content.tagvalue_id = arr3.join(",");
//				}
//			}
			var j = timeout_json(data, $window);
			if(j == false) {
				return false;
			}
			$scope.initData();
		});
	} else {
		opt_type = 0;
		$scope.initData();
	}
});

//open edit Layer
var editExaDataLayer = null;
var queryType;
$('.editExaDataBtn').live('click', function() {
	var editExaDataLayer = $.layer({
		type: 1,
		title: false,
		area: ['700', 'auto'],
		border: [0], //去掉默认边框
		shade: [0.3, '#000'], //去掉遮罩
		closeBtn: [0, false], //去掉默认关闭按钮
		fadeIn: 500,
		move: "#editExaData_tile",
		page: {
			dom: '#editExaDataLayer'
		}
	});
	//自设关闭
	$('#editExaDataLayer > .closeBtn,#editExaDataLayer .cancelLayer,#editExaSubmitBtn').live('click', function() {
		layer.close(editExaDataLayer);
	});
});

var edit = {
	"qCompanyList": function(_this, ruleArr, queryValue) {
		var queryUrl = {
			tagvalue_id: "Tagvalue/queryTagvalue.do"
		};
		var queryParams = {
			tagvalue_id: {
				tag_value: queryValue,
				pageIndex: 1,
				pageSize: 10000000
			}
		};
		var showTypeParams = {
			tagvalue_id: {
				id: "tagvalue_id",
				name: "tag_value",
				tag_type:"tag_type"
			}
		}
		var _obj = $("#CustomsAreaList");
		$.ajax({
			type: "POST",
			url: basePath + queryUrl[eval('queryType')],
			data: queryParams[eval('queryType')],
			success: function(data) {
				if(data.returnCode == 10000) {
					var s2 = data.returnData.length;
					var showTypeParamId = showTypeParams[eval('queryType')].id;
					var showTypeParamName = showTypeParams[eval('queryType')].name;
					var showTypeParamtype = showTypeParams[eval('queryType')].tag_type;
					var showTypeParamType = showTypeParams[eval('queryType')].tag_type;
					if(s2 > 0) {
						var htmls = "";
						var checkedHtmls = "";

						for(var i = 0; i < s2; i++) {
							var checkedBtn = "";
							var checked = "";
							var ruleId2 = data.returnData[i][eval("showTypeParamId")];
							var checkeddefault = "";
							var num = ruleArr.length;
							var tf = null;
							for(var nn = 0; nn < num; nn++) {
								if(ruleId2 == ruleArr[nn]) {
									checkedBtn = "true";
									checked = "checked";
									checkeddefault = "true";
									tf = true;
									break;
								} else {
									checkedBtn = "false";
									checkeddefault = "false";
									checked = "";
									tf = false;
								}
							}
							if(tf == true) {
								checkedHtmls += "<div class='infoLlist' title='" + data.returnData[i][eval("showTypeParamName")] + "'><span class='ui_checkbox " + checked + "' t-id= '" + data.returnData[i][eval("showTypeParamId")] + "' checkedBtn='" + checkedBtn + "' checkeddefault='" + checkeddefault + "'></span> <font>" +data.returnData[i][eval("showTypeParamtype")]+"-"+ data.returnData[i][eval("showTypeParamName")] + "</font></div>";
								checkedHtmls += "<div class='infoLlist' title='" + data.returnData[i][eval("showTypeParamName")] + "'><span class='ui_checkbox " + checked + "' t-id= '" + data.returnData[i][eval("showTypeParamId")] + "' checkedBtn='" + checkedBtn + "' checkeddefault='" + checkeddefault + "'></span> <font>" + data.returnData[i][eval("showTypeParamType")] +"-"+ data.returnData[i][eval("showTypeParamName")] + "</font></div>";
							} else if(tf == false) {
								htmls += "<div class='infoLlist' title='" + data.returnData[i][eval("showTypeParamName")] + "'><span class='ui_checkbox " + checked + "' t-id= '" + data.returnData[i][eval("showTypeParamId")] + "' checkedBtn='" + checkedBtn + "' checkeddefault='" + checkeddefault + "'></span> <font>" +data.returnData[i][eval("showTypeParamtype")]+"-"+ data.returnData[i][eval("showTypeParamName")] + "</font></div>";
								htmls += "<div class='infoLlist' title='" + data.returnData[i][eval("showTypeParamName")] + "'><span class='ui_checkbox " + checked + "' t-id= '" + data.returnData[i][eval("showTypeParamId")] + "' checkedBtn='" + checkedBtn + "' checkeddefault='" + checkeddefault + "'></span> <font>" + data.returnData[i][eval("showTypeParamType")] +"-"+ data.returnData[i][eval("showTypeParamName")] + "</font></div>";

							}
						}
						$("#checkQueryInput").val("");
						$("#editExaData_tile").text(_this.attr("title") + "列表");
						$("#editExaData_listName").text(_this.attr("title") + "名称");
						_obj.html(checkedHtmls + htmls + "<div class='clear'></div>");
						checkTrueFalse();
					}
					if(s2 < 1) {
						_obj.html("<br><bR><p align='center'>很遗憾，没有查询到相关的数据！</p><br><bR>");
					}
				} else if(data.returnCode == 999994) {
					setUserTimeout(data);
				} else {
					layer.msg(data.returnMessage, 2, -1);
				}
			},
			error: function(message) {
				layer.msg("操作失败，请重试！", 2, -1);
			},
			beforeSend: function() {
				var imgGif = "<p class='loadingGif'></p>";
				_obj.html(imgGif);
			}
		});
	},
	"quyeryCheck": function(ids, names) {
		var $selectShowSpan = $(".editExaDataBtn[type='" + queryType + "']");
		var $showSpan = $selectShowSpan.parent().prev("span");
		$selectShowSpan.attr({
			ids: ids
		});
		$showSpan.text(names);
	}
}
$(".infoLlist .ui_checkbox").live("click", function() {
	if($(this).attr("checkedBtn") == "true") {
		$(this).attr("checkedBtn", "false");
		$(this).removeClass("checked");
	} else {
		$(this).attr("checkedBtn", "true");
		$(this).addClass("checked");
	}
});

$(".editExaDataBtn").live("mouseover", function() {
	var ruleArr = $(this).attr('ids').split(",");
	queryType = $(this).attr('type');
	var params = "";
	edit.qCompanyList($(this), ruleArr, params);
});

$("#checkQueryBtn").live("click", function() {
	publicQDataList3($("#checkQueryInput"));
});
$('.enterKeyDownElement2').keydown(function(e) {
	if(e.keyCode == 13) {
		publicQDataList3($("#checkQueryInput"));
	}
});

function publicQDataList3(_this) {
	var kV = $.trim(_this.val());
	$("#CustomsAreaList .infoLlist").each(function() {
		var name = $(this).children("font").text();
		var isOf = $.trim(name.indexOf(kV));
		if(isOf > -1) {
			$(this).show();
		} else {
			$(this).hide();
		}
	});

}

$("#editExaSubmitBtn").live("click", function() {
	var trueArr = new Array();
	var trueStrArr = new Array();
	$("#CustomsAreaList .ui_checkbox").each(function() {
		var id = $(this).attr("t-id");
		var name = $(this).next("font").text();
		var checkedbtn = $(this).attr("checkedbtn");
		var checkeddefault = $(this).attr("checkeddefault");
		if(checkedbtn == "true") {
			trueArr.push(id);
			trueStrArr.push(name);
		};
	});
	var trueArrs = "";
	var trueStrArrs = "";
	if(trueArr.length > 0) {
		trueArrs = trueArr.join(",");
		trueStrArrs = trueStrArr.join(",");
	}
	edit.quyeryCheck(trueArrs, trueStrArrs);
	$(".xubox_main").css("cssText", "height:45px!important; z-index:198916;");
});

$(".selectAllAreaGoGo .allSel").live("click", function() {
	var checkedbtn = $(this).attr("checkedbtn");
	if(checkedbtn == "true") {
		$("#CustomsAreaList .infoLlist .ui_checkbox").addClass("checked").attr("checkedbtn", "true");
	} else {
		$("#CustomsAreaList .infoLlist .ui_checkbox").removeClass("checked").attr("checkedbtn", "false");
	}
});

$(".selectAllAreaGoGo .reDefault").live("click", function() {
	$("#CustomsAreaList .infoLlist .ui_checkbox").each(function() {
		var checkeddefault = $(this).attr("checkeddefault");
		if(checkeddefault == "true") {
			$(this).addClass("checked").attr("checkedbtn", "true");
		} else {
			$(this).removeClass("checked").attr("checkedbtn", "false");
		}
	});
	checkTrueFalse();
});

$("#CustomsAreaList .infoLlist .ui_checkbox").live("click", function() {
	checkTrueFalse();
});

function checkTrueFalse() {
	var isTrue = "true";
	$("#CustomsAreaList .infoLlist .ui_checkbox").each(function() {
		var checkedbtn = $(this).attr("checkedbtn");
		if(checkedbtn == "false") {
			isTrue = "false";
			return;
		}
	});
	if(isTrue == "false") {
		$(".selectAllAreaGoGo .allSel").removeClass("checked").attr("checkedbtn", "false");
	} else {
		$(".selectAllAreaGoGo .allSel").addClass("checked").attr("checkedbtn", "true");
	}
}

app.directive('agSelect', function($http) {
	return {
		restrict: 'AE',
		scope: {
			domain_name: '=domainName',
			domain_id: '=domainId'
		},
		template: '<div class="ui_select fl"><input class="ui_s_t" id="sName" type="text" ng-bind="stxt" ng-model="stxt"><div class="ui_s_bk"><a href="javascript:void(0)" ng-repeat="key in datas | filter: {domain_name:stxt}"  ng-bind="key.domain_name" data-id="{{key.domain_id}}"></a></div></div>',
		controller: function($scope, $element, $attrs) {
			var a = $element.find('.ui_s_t'),
				b = $element.find('.ui_s_bk'),
				c = $attrs.ajaxs,
				d = $attrs.loadajaxs;
			$element.children('.ui_select').css({
				'zIndex': 99,
				"margin-left": 0
			});
			$element.bind('click', function() {
				b.slideDown();
			});
			$element.bind('mouseleave', function() {
				if(a.text() != "") {
					b.hide();
				}else{
                	b.find('.ui_s_t').blur();
                	b.hide();
                }
			});
		},
		link: function($scope, $element, $attrs) {
			$scope.stxt = '';
			var a = $element.find('.ui_s_t'),
				b = $element.find('.ui_s_bk'),
				c = $attrs.ajaxs;
			if(c != undefined) {
				$http.get(c).success(function(data) {
					$scope.datas = data.returnData;
				});
			}
//			a.click(function() {
//				$scope.stxt = undefined;
//				$scope.$apply();
//			});
			b.find('a').live("click", function() {
				b.hide();
				$(this).addClass('cur').siblings().removeClass('cur');
				a.val($(this).text());
				$scope.stxt = $(this).text();
//				$("#sName").val($(this).text());

				if($attrs.domainName != undefined) {
					$scope.domain_name = $(this).text();
					if(parseInt($(this).attr('data-id')) == 0) {
						$scope.domain_name = undefined;
					}
				}
				if($attrs.domainId != undefined) {
					$scope.domain_id = $(".ui_s_bk .cur").attr("data-id");
				}
				$scope.$apply();
				$("#domainIdSel").val($(".ui_s_bk .cur").attr("data-id"));
				return false;
			});
		}
	}
});